Page({
  data: {
    userInfo: {},
    earnMethods: [],
    exchangeItems: [],
    exchangeHistory: []
  },

  onLoad() {
    this.loadUserInfo();
    this.loadEarnMethods();
    this.loadExchangeItems();
    this.loadExchangeHistory();
  },

  onShow() {
    // 页面显示时刷新兑换记录，确保状态是最新的
    this.loadExchangeHistory();
  },

  // 加载用户信息
  loadUserInfo() {
    const app = getApp();
    const userInfo = app.globalData.userInfo || {};
    this.setData({
      userInfo: userInfo
    });
  },

  // 加载赚积分方式
  loadEarnMethods() {
    // 积分规则可以从后端获取，这里先使用静态数据
    const earnMethods = [
      {
        id: 1,
        icon: '📝',
        title: '发布菜谱',
        desc: '发布优质菜谱获得积分',
        points: 50
      },
      {
        id: 2,
        icon: '📹',
        title: '发布视频',
        desc: '发布美食视频获得积分',
        points: 80
      },
      {
        id: 3,
        icon: '💬',
        title: '评论互动',
        desc: '评论其他用户内容',
        points: 10
      },
      {
        id: 4,
        icon: '❤️',
        title: '点赞收藏',
        desc: '点赞收藏优质内容',
        points: 5
      },
      {
        id: 5,
        icon: '📅',
        title: '每日签到',
        desc: '每日签到获得积分',
        points: 20
      },
      {
        id: 6,
        icon: '👥',
        title: '邀请好友',
        desc: '邀请好友注册获得积分',
        points: 100
      }
    ];

    this.setData({
      earnMethods: earnMethods
    });
  },

  // 加载兑换商品
  loadExchangeItems() {
    let token = '';
    try {
      token = wx.getStorageSync('token');
    } catch (e) {
      console.error('获取token失败', e);
    }

    wx.showLoading({
      title: '加载中...',
      mask: true
    });

    // 调用后端接口获取商品列表（多表联查，支持分页和筛选）
    wx.request({
      url: 'http://localhost:8080/point/goods/list-with-stats',
      method: 'GET',
      header: {
        'Authorization': token,
        'Content-Type': 'application/json'
      },
      data: {
        pageNum: 1,
        pageSize: 6 // 显示6个商品
      },
      success: (res) => {
        wx.hideLoading();
        console.log('商品列表API返回数据:', res.data);
        
        if (res.data.code === 200) {
          const goodsList = res.data.rows || [];
          // 转换数据格式，根据实际API返回的字段名
          const exchangeItems = goodsList.map(item => ({
            id: item.id,
            title: item.name || item.title,
            imageUrl: this.getFullImageUrl(item.coverImg || item.imageUrl),
            points: item.point || item.points || item.pointPrice,
            originalPrice: item.originalPrice || item.marketPrice,
            stock: item.stock || 0,
            sales: item.sales || 0,
            validityDays: item.validityDays || 0,
            exchangeCount: item.exchangeCount || 0,
            status: item.status
          }));

          console.log('转换后的商品列表:', exchangeItems);

          this.setData({
            exchangeItems: exchangeItems
          });
        } else {
          // 如果获取失败，使用推荐商品接口作为备选
          this.loadRecommendedGoods();
        }
      },
      fail: (err) => {
        wx.hideLoading();
        console.error('获取商品列表失败', err);
        // 使用推荐商品接口作为备选
        this.loadRecommendedGoods();
      }
    });
  },

  // 加载推荐商品
  loadRecommendedGoods() {
    let token = '';
    try {
      token = wx.getStorageSync('token');
    } catch (e) {
      console.error('获取token失败', e);
    }

    wx.request({
      url: 'http://localhost:8080/point/goods/recommended',
      method: 'GET',
      header: {
        'Authorization': token,
        'Content-Type': 'application/json'
      },
      success: (res) => {
        if (res.data.code === 200) {
          const goods = res.data.data || [];
          const exchangeItems = goods.map(item => ({
            id: item.id,
            title: item.name || item.title,
            imageUrl: this.getFullImageUrl(item.coverImg || item.imageUrl),
            points: item.point || item.points || item.pointPrice,
            originalPrice: item.originalPrice || item.marketPrice
          }));

          this.setData({
            exchangeItems: exchangeItems
          });
        }
      },
      fail: (err) => {
        console.error('获取推荐商品失败', err);
        // 如果都失败了，使用默认数据
        this.setDefaultGoods();
      }
    });
  },

  // 设置默认商品数据
  setDefaultGoods() {
    const defaultGoods = [
      {
        id: 1,
        title: '美食课程券',
        imageUrl: 'https://picsum.photos/200/200?random=1',
        points: 500,
        originalPrice: '99'
      },
      {
        id: 2,
        title: '厨房用品套装',
        imageUrl: 'https://picsum.photos/200/200?random=2',
        points: 800,
        originalPrice: '158'
      }
    ];

    this.setData({
      exchangeItems: defaultGoods
    });
  },

  // 获取完整的图片URL
  getFullImageUrl(imagePath) {
    if (!imagePath) return '';
    if (imagePath.startsWith('http')) return imagePath;
    return 'https://gzq123.oss-cn-beijing.aliyuncs.com/' + imagePath;
  },

  // 加载兑换记录
  loadExchangeHistory() {
    const app = getApp();
    const userInfo = app.globalData.userInfo || {};
    
    if (!userInfo.id) {
      return;
    }

    let token = '';
    try {
      token = wx.getStorageSync('token');
    } catch (e) {
      console.error('获取token失败', e);
    }

    // 调用后端接口获取用户兑换历史
    wx.request({
      url: 'http://localhost:8080/point/order/history/' + userInfo.id,
      method: 'GET',
      header: {
        'Authorization': token,
        'Content-Type': 'application/json'
      },
      data: {
        page: 1,
        pageSize: 5 // 显示5条记录，让用户看到更多状态
      },
      success: (res) => {
        console.log('兑换历史API返回数据:', res.data);
        
        if (res.data.code === 200) {
          const history = res.data.data || [];
          
          // 提取第一个订单中的users数据并赋值给userInfo
          if (history.length > 0 && history[0].users) {
            const usersData = history[0].users;
            console.log('提取到的users数据:', usersData);
            
            // 将users数据赋值给data中的userInfo，并将totalPoint映射为points
            const mappedUserInfo = {
              ...usersData,
              points: usersData.totalPoint || 0 // 将totalPoint映射为points字段
            };
            
            this.setData({
              userInfo: mappedUserInfo
            });
            
            // 同时保存到app.js的globalData.userInfo1中
            app.globalData.userInfo1 = usersData;
            wx.setStorageSync('userInfo1', usersData);
            
            console.log('已更新userInfo数据:', mappedUserInfo);
            console.log('已保存到globalData.userInfo1:', app.globalData.userInfo1);
          }
          
          // 转换数据格式，根据实际API返回的字段名和嵌套结构
          const exchangeHistory = history.map(item => ({
            id: item.id,
            title: item.goodsName || (item.mallGoods ? item.mallGoods.name : ''),
            imageUrl: this.getFullImageUrl(item.mallGoods ? item.mallGoods.coverImg : ''),
            time: item.createTime || '',
            status: this.getStatusText(item.status),
            orderSn: item.orderSn || '',
            trackingNumber: item.logistics ? item.logistics.expressNo : '',
            expressCompany: item.logistics ? item.logistics.expressCompany : '',
            points: item.point || 0
          }));

          console.log('转换后的兑换历史:', exchangeHistory);

          this.setData({
            exchangeHistory: exchangeHistory
          });
        }
      },
      fail: (err) => {
        console.error('获取兑换历史失败', err);
      }
    });
  },

  // 积分明细
  onPointsHistory() {
    wx.navigateTo({
      url: '/my/pages/points-detail/points-detail'
    });
  },

  // 兑换商品
  onExchangeItem(e) {
    const item = e.currentTarget.dataset.item;
    
    if (this.data.userInfo.points < item.points) {
      wx.showToast({
        title: '积分不足',
        icon: 'none'
      });
      return;
    }

    // 跳转到商品详情页面
    wx.navigateTo({
      url: `/my/pages/goods-detail/goods-detail?id=${item.id}`
    });
  },

  // 查看全部记录
  onViewAllHistory() {
    wx.navigateTo({
      url: '/my/pages/exchange-history/exchange-history'
    });
  },

  // 查看更多商品
  onViewMoreGoods() {
    wx.navigateTo({
      url: '/my/pages/goods-list/goods-list'
    });
  },

  // 查看兑换记录详情
  onViewHistoryDetail(e) {
    const item = e.currentTarget.dataset.item;
    wx.navigateTo({
      url: `/my/pages/exchange-detail/exchange-detail?id=${item.id}`
    });
  },

  // 分享给朋友
  onShareAppMessage() {
    return {
      title: '积分商城',
      path: '/my/pages/points-mall/points-mall'
    };
  },

  // 分享到朋友圈
  onShareTimeline() {
    return {
      title: '积分商城'
    };
  },

  // 根据状态码获取文本描述
  getStatusText(status) {
    switch (status) {
      case 0:
        return 'pending';
      case 1:
        return 'shipped';
      case 2:
        return 'completed';
      default:
        return 'pending';
    }
  }
}); 